import { cloneDeep } from 'lodash-es'
import { ENERGY_COMPREHENSIVE } from '../components'
import type { StatisticsDataItem } from '../components/type'
import { statisticalAnalysisApi } from '@/api'
import type {
  StatisticalAnalysisSelectRegionEnergyConsumeSumResultItem as A,
  StatisticalAnalysisSelectRegionEnergyConsumeListParams as B,
  StatisticalAnalysisPublicParams,
} from '@/types'
/** 获取表头 */
function completeEnergyHeader(array: C[]) {
  const hander = []
  for (const item of array) {
    hander.push(...item.list.map(item => item.pointName))
  }
  // 去重
  return [...new Set(hander)]
}

interface C {
  time: string
  list: {
    pointName: string
    pointId: string
    val: string
  }[]
}

export function useQueryLists() {
  const [energyTypes, setEnergyTypes] = useShallowState<
    A[]
  >([])
  const [allEnergyTypes, setAllEnergyTypes]
    = useShallowState<any[]>([])
  const [energyData, setEnergyData] = useShallowState<C[]>(
    [],
  )

  const cardData = computed(() => {
    const all = unref(allEnergyTypes)
    const target = unref(energyTypes)
    const o = target.map((item) => {
      if (!item.energyId) {
        return {
          type: ENERGY_COMPREHENSIVE,
          title: '综合能耗',
          unit: '吨标准煤',
          /** 同比 */
          yoy:
            item.energyCompanyConsumePercentage?.toString()
            ?? '',
          /** 环比 */
          qoq:
            item.energyChainConsumePercentage?.toString()
            ?? '',
          value: item.energyConsume,
        }
      }
      const c = all.find(v => v.id === item.energyId)
      if (!c)
        return undefined
      return {
        type: c.id.toString(),
        title: c.name,
        unit: c.energyUnit,
        /** 同比 */
        yoy: item.energyCompanyConsumePercentage,
        /** 环比 */
        qoq: item.energyChainConsumePercentage,
        value: item.energyConsume,
      }
    })

    return o.filter(v =>
      Boolean(v),
    ) as StatisticsDataItem[]
  })

  const x = computed(() => {
    return unref(energyData).map(v =>
      /\d{4}-\d{2}-\d{2}\s+\d{2}/.test(v.time)
        ? `${v.time}:00`
        : v.time,
    )
  })
  const l = computed(() => {
    const d = unref(energyData)
    return completeEnergyHeader(d)
  })
  const y = computed(() => {
    const d = unref(energyData).reduce(
      (pre: any, cur: any) => {
        const o = []
        if (cur.list.length === 0) {
          o.push(
            ...Array.from({ length: l.value.length }).fill(undefined),
          )
        }
        else {
          o.push(...cur.list.map((v: any) => v?.val))
        }
        // 处理每月数据数量不相同的情况
        if (o.length < l.value.length) {
          o.push(
            ...Array.from({ length: l.value.length - o.length }).fill(
              undefined,
            ),
          )
        }
        return [...pre, o]
      },
      [] as any,
    )
    return d
  })

  const columns = computed(() => {
    return ['时间', ...unref(l)]
  })
  const tableData = computed(() => {
    const d = unref(x)
    const arr: any[] = Array.from({ length: l.value.length }).fill(0)
    const o = unref(y).map((v: any, i: number) => {
      const _v: string[] = []

      v.forEach((c: any, j: number) => {
        if (c) {
          // 合计计算
          arr[j] += +c
          _v.push((+c).toFixed?.(2))
        }
        else {
          // 处理为空的情况
          _v.push('-')
        }
      })

      return [d[i], ..._v]
    })
    o.push(['合计', ...arr.map(item => item.toFixed(2))])

    return o
  })
  const emptyPie = computed(() => {
    const tail
      = unref(tableData)[unref(tableData).length - 1]
    if (!tail)
      return true
    return Number(tail[1]) <= 0 && Number(tail[2]) <= 0
  })

  const pieData = computed(() => {
    const d = unref(tableData)
    const data = cloneDeep(d.at(-1)!)
    data.shift()
    const source = l.value.map((title, i) => [
      title,
      data[i],
    ])
    return d.length > 0
      ? {
          source: [['区域能耗占比', '能耗量'], ...source],
        }
      : {
          source: [],
        }
  })

  /** 获取所有能源类型 */
  async function getAllEnergyTypes(
    dataTime: StatisticalAnalysisPublicParams['dataTime'],
  ) {
    const { data: all }
      = await statisticalAnalysisApi.selectRegionEnergyType(
        dataTime,
      )
    setAllEnergyTypes(all || [])
  }
  async function getEnergyTypes(
    query: StatisticalAnalysisPublicParams,
  ) {
    const { data: res }
      = await statisticalAnalysisApi.selectRegionEnergyConsumeSum(
        query,
      )
    setEnergyTypes(res || [])
  }
  async function getEnergyData(query: B) {
    const { data: a }
      = await statisticalAnalysisApi.selectRegionEnergyConsumeList(
        query,
      );
    (a || []).forEach((item: any) => {
      item.list = item.list || []
    })
    setEnergyData(a)
  }

  return {
    /** 能源类型列表 */
    energyTypes,
    /** 能源数据列表 */
    energyData,
    emptyPie,

    /** 能源数据表格表头 */
    columns,
    /** 能源数据列表表格数据 */
    tableData,

    /** 堆叠图x轴数据 */
    x,
    /** 堆叠图y轴数据 */
    y,
    /** legend 数据列 */
    l,
    /** pie图数据列 */
    pieData,
    /** 能源类型选项卡数据 */
    cardData,
    /** 获取能源类型列表 */
    getEnergyTypes,
    /** 获取能源数据列表 */
    getEnergyData,
    /** 设置能源类型列表 */
    setEnergyTypes,
    /** 设置能源数据列表 */
    setEnergyData,
    /** 获取所有能源类型 */
    getAllEnergyTypes,
  }
}
